package com.pzhu.gmall.web.intercepter;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.pzhu.gmall.commons.utils.HttpclientUtil;
import com.pzhu.gmall.commons.utils.MD5Utils;
import com.pzhu.gmall.web.annotations.LoginRequired;
import com.pzhu.gmall.web.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author 刘鹏 liupeng
 * @date 2019/11/19
 **/
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截代码

        //验证是否登录
        Boolean success = verifyLogin(request, response);

        //判断被拦截的方法的注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        LoginRequired methodAnnotation = handlerMethod.getMethodAnnotation(LoginRequired.class);

        if (methodAnnotation != null) {
            //需要登录
            if (methodAnnotation.needSuccess()) {
                //没有登录
                if (!success) {
                    //重定向到登录页面
                    StringBuffer requestURL = request.getRequestURL();
                    response.sendRedirect("http://127.0.0.1:9001/index?ReturnUrl=" + requestURL);
                    return false;
                }
            }
        }
        return true;
    }

    private Boolean verifyLogin(HttpServletRequest request, HttpServletResponse response) {
        String token = "";
        String oldToken = CookieUtil.getCookieValue(request, "oldToken", true);
        if (StringUtils.isNotBlank(oldToken)) {
            //如果 cookie中有token说明登录过
            token = oldToken;
        }
        //登录时触发
        String newToken = request.getParameter("token");
        if (StringUtils.isNotBlank(newToken)) {
            token = newToken;
        }
        //通过httpclient调用认证中心，验证token真伪
        String ip = request.getHeader("x-forwarded-for"); //通过nginx章法的客户端Ip
        if (StringUtils.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        ip = MD5Utils.md5(ip);
        String result = HttpclientUtil.doGet("http://127.0.0.1:9001/verify?token=" + token + "?ip=" + ip);
        if (!"fail".equals(result)) {
            CookieUtil.setCookie(request, response, "oldToken", token, 2 * 60 * 60, true);
            Map<String, String> map = JSON.parseObject(result, Map.class);
            request.setAttribute("memberId", map.get("memberId"));
            request.setAttribute("nickname", map.get("nickname"));
            return true;
        }
        return false;
    }

}
